import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:markdown/markdown.dart' as md;
import 'package:flutter_math_fork/flutter_math.dart';
import 'latex_syntax.dart';

/// 自定义Markdown表格构建器
/// 支持LaTeX公式渲染的自定义Markdown表格构建器
class CustomMarkdownTableBuilder extends MarkdownElementBuilder {
  final TextStyle? style;
  final double? textScaleFactor;

  CustomMarkdownTableBuilder({this.style, this.textScaleFactor});

  @override
  Widget? visitElementAfter(md.Element element, TextStyle? preferredStyle) {
    if (element.tag != 'table') return null;
    
    final baseStyle = style ?? preferredStyle ?? const TextStyle();
    
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: _buildTable(element, baseStyle),
    );
  }
  
  /// 构建表格Widget
  Widget _buildTable(md.Element tableElement, TextStyle baseStyle) {
    List<TableRow> rows = [];
    
    for (final child in tableElement.children ?? <md.Node>[]) {
      if (child is md.Element) {
        if (child.tag == 'thead' || child.tag == 'tbody') {
          // 处理表头或表体
          for (final rowChild in child.children ?? <md.Node>[]) {
            if (rowChild is md.Element && rowChild.tag == 'tr') {
              rows.add(_buildTableRow(rowChild, baseStyle, child.tag == 'thead'));
            }
          }
        } else if (child.tag == 'tr') {
          // 直接处理表格行
          rows.add(_buildTableRow(child, baseStyle, false));
        }
      }
    }
    
    return Table(
      border: TableBorder.all(color: Colors.grey.shade300),
      children: rows,
    );
  }
  
  /// 构建表格行
  TableRow _buildTableRow(md.Element rowElement, TextStyle baseStyle, bool isHeader) {
    List<Widget> cells = [];
    
    for (final child in rowElement.children ?? <md.Node>[]) {
      if (child is md.Element && (child.tag == 'td' || child.tag == 'th')) {
        cells.add(_buildTableCell(child, baseStyle, isHeader));
      }
    }
    
    return TableRow(children: cells);
  }
  
  /// 构建表格单元格
  Widget _buildTableCell(md.Element cellElement, TextStyle baseStyle, bool isHeader) {
    final cellStyle = isHeader 
        ? baseStyle.copyWith(fontWeight: FontWeight.bold)
        : baseStyle;
    
    return Container(
      padding: const EdgeInsets.all(8.0),
      child: _buildCellContent(cellElement, cellStyle),
    );
  }
  
  /// 构建单元格内容，支持LaTeX公式
  Widget _buildCellContent(md.Element cellElement, TextStyle cellStyle) {
    String content = _extractTextContent(cellElement);
    
    // 检查是否包含LaTeX公式
    if (content.contains(r'$')) {
      return _buildMixedContent(content, cellStyle);
    } else {
      return Text(
        content,
        style: cellStyle,
        textScaleFactor: textScaleFactor ?? 1.0,
      );
    }
  }
  
  /// 构建包含LaTeX公式的混合内容
  Widget _buildMixedContent(String content, TextStyle cellStyle) {
    List<Widget> widgets = [];
    
    // 使用正则表达式分割文本和LaTeX公式
    RegExp latexRegex = RegExp(r'\$([^\$]+)\$');
    int lastEnd = 0;
    
    for (Match match in latexRegex.allMatches(content)) {
      // 添加LaTeX公式前的文本
      if (match.start > lastEnd) {
        String textBefore = content.substring(lastEnd, match.start);
        if (textBefore.isNotEmpty) {
          widgets.add(Text(
            textBefore,
            style: cellStyle,
            textScaleFactor: textScaleFactor ?? 1.0,
          ));
        }
      }
      
      // 添加LaTeX公式
      String latexContent = match.group(1) ?? '';
      widgets.add(_buildLatexWidget(latexContent, cellStyle));
      
      lastEnd = match.end;
    }
    
    // 添加最后剩余的文本
    if (lastEnd < content.length) {
      String textAfter = content.substring(lastEnd);
      if (textAfter.isNotEmpty) {
        widgets.add(Text(
          textAfter,
          style: cellStyle,
          textScaleFactor: textScaleFactor ?? 1.0,
        ));
      }
    }
    
    return Wrap(
      crossAxisAlignment: WrapCrossAlignment.center,
      children: widgets,
    );
  }
  
  /// 构建LaTeX Widget
  Widget _buildLatexWidget(String latexContent, TextStyle cellStyle) {
    try {
      return Math.tex(
        latexContent,
        textStyle: cellStyle,
        mathStyle: MathStyle.text,
      );
    } catch (e) {
      // 如果LaTeX解析失败，显示原始文本
      return Text(
        '\$${latexContent}\$',
        style: cellStyle,
        textScaleFactor: textScaleFactor ?? 1.0,
      );
    }
  }
  
  /// 提取元素的文本内容
  String _extractTextContent(md.Element element) {
    StringBuffer buffer = StringBuffer();
    _extractTextRecursive(element, buffer);
    return buffer.toString().trim();
  }
  
  /// 递归提取文本内容
  void _extractTextRecursive(md.Node node, StringBuffer buffer) {
    if (node is md.Text) {
      buffer.write(node.text);
    } else if (node is md.Element) {
      for (final child in node.children ?? <md.Node>[]) {
        _extractTextRecursive(child, buffer);
      }
    }
  }
}